<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2017/1/12
 * Time: 14:25
 */

namespace SDXApi\Controller;
use Think\Controller;
use Think\Crypt\Driver\Think;
use SDXApi\Service\OpensearchService;
use SDXApi\Service\UserBehavior;

class OpensearchController extends Controller{
    protected $client;
    protected $app_name = 'shidexian';
    protected $wid = 8;
    protected $origin;
    protected $brand_id;
    protected $cat_id;
    protected $page_size = 15;

    protected function _initialize()
    {
        header("Access-Control-Allow-Origin: *");
        if($_SERVER['SERVER_NAME'] == 'api.shidexian.com'){
            $opts = array('host'=>"http://intranet.opensearch-cn-hangzhou.aliyuncs.com");
        }else{
            $opts = array('host'=>"http://opensearch-cn-hangzhou.aliyuncs.com");
        }

        $this->client = new \Vendor\OpenSearch\CloudsearchClient(C('ALIYUN_AKID'), C('ALIYUN_AKSECRET'), $opts, "aliyun");

    }


    //搜索结果列表
    public function lists(){

        $opensearch = new OpensearchService();

        $keyword = I('post.keyword', '', 'trim'); //搜索关键词
        $sort_field = I('post.sort_field');  //排序字段（价格：shop_price ；评论：comment ）
        $sort_type = I('post.sort_type'); //排序类型（1:升序；2：降序）
        $page_num = I('post.page',1, 'int'); //分页
        $cat_id = $cat_id2 = I('post.cat_id', 0, 'int');//分类id （一级分类id）
        $cat_child_id = I('post.cat_child_id'); //子分类id 多个用 '|'分隔  如 356|1128
        $no_goods_data = I('no_goods_data', 0, 'int'); //是否不返回商品数据：0否，1是
        $this->wid = I('post.wid',8, 'int');
        $user_id = I('post.uid',0, 'int');
        $this->origin = I('post.origin'); //产地（筛选） 多个用 '|'分隔  如 香港|俄罗斯
        $this->brand_id = I('post.brand_id'); //品牌id（筛选） 多个用 '|'分隔  如 356|1128

        $md5_key = md5($user_id.'_'.$keyword.'_'.$sort_field.'_'.$sort_type.'_'.$page_num.'_'.$cat_id.'_'.$cat_child_id.'_'.$no_goods_data.'_'.$this->origin.'_'.$this->brand_id.'_'.$this->wid);

        $sort = 0;
        if($sort_field=='shop_price' && $sort_type==1){
            $sort = 1;
        }
        if($sort_field=='shop_price' && $sort_type==2){
            $sort = 2;
        }
        if($sort_field=='comment' && $sort_type==1){
            $sort = 3;
        }
        if($sort_field=='comment' && $sort_type==2){
            $sort = 4;
        }

        $search_type = 1;//自然搜索

        //不传关键词，用cat_id查询相应分类名称
        if($cat_id && !$keyword){
            $category = M('Category')->field('cat_name')->find($cat_id);
            $keyword = $category['cat_name'];
            $search_type = 2;//分类搜索
        }

        if(!$keyword || !$this->wid) returnApiError('参数有误');

        //    	统计搜索热词
        $hotId = I('post.hot_id', 0, 'intval');
        if (!empty($hotId)) {
            $search_type = 3;//热词点击搜索
            $hotModel = D('SearchHot');
            $hotModel->add_search_hot_count($hotId);
        }

        $search_list = S($md5_key);

        if($search_list){
            if ($page_num == 1) {
                $this->add_search_keyword($user_id, $search_type, $sort, $keyword, $search_list['total']);
            }
            returnApiSuccess($search_list);
        }

        //$cat_id = $cat_child_id ? $cat_child_id : $cat_id;
        $cat_id_list = '';
        if($cat_id) {
            $this->set_cat_id($cat_id);
            $cat_id_list = $this->cat_id;
        }

        if($cat_child_id){
            $this->cat_id = $cat_child_id;
        }
        //print_r($this->cat_id);exit;

        if($sort_type){
            if($sort_type == 1)
                $sort_type = '+';
            elseif($sort_type == 2)
                $sort_type = '-';
            else
                returnApiError('sort_type参数有误');
        }

        //返回商品数据
        if($no_goods_data == 0) {

            //查询会员等级
            if ($user_id) {
                $user = M("Users")->field('user_rank')->find($user_id);
            }

            $firstpage = ($page_num - 1) * $this->page_size;
            $search_list = $this->get_search_list($keyword, $firstpage, $sort_field, $sort_type, $user['user_rank']);

            if ($page_num == 1) {
                $this->add_search_keyword($user_id, $search_type, $sort, $keyword, $search_list['total']);
            }

            $id_list = $this->get_goods_id($search_list['items']);

            if (!$id_list){
                returnApiError('没有数据');
            }

            $goods_list = D('Goods')->get_search_goods_by_id(implode(',', $id_list), $user_id, $this->wid);

            if (!$goods_list){
                returnApiError('没有数据');
            }

            $return_data = array();
            $pagecount = ceil($search_list['total'] / $this->page_size);

            if ($pagecount <= $page_num) {
                //判断是否为最后一页
                $return_data['is_bottom'] = 1;
            } else {
                $return_data['is_bottom'] = 0;
            }
            $return_data['total'] = $search_list['total'];
            $return_data['page'] = array(
                'firstpage' => $firstpage,
                'pagecount' => $pagecount,
                'pagesize' => $this->page_size
            );
            $return_data['goodssaleslist'] = $goods_list;

        }
        $return_data['origin_list'] = $this->get_origin($keyword);
        $return_data['brand_list'] = $this->get_brand($keyword);
        $return_data['catelist'] = $this->get_category($keyword, $cat_id_list);
        $return_data['cat_child_list'] = $this->get_son_category($keyword, $cat_id_list);


        if($goods_list){
            //添加到用户行为
            //$param = array('isertList', $user_id, 'view', $goods_list, I('wid'), 2, $keyword, $keyword_id);
            //\Think\Hook::listen('receng', $param);

            S($md5_key, $return_data, 5);
        }

        returnApiSuccess($return_data);
    }

    /**
     * @author Min
     * @param $user_id
     * @param $search_type
     * @param $sort
     * @param $keyword
     * @param $total
     */
    protected function add_search_keyword($user_id, $search_type, $sort, $keyword, $total)
    {
        //记录搜索记录
        if (!empty($keyword)) {
            $search_data = array();
            $search_data['params'] = I('post.params');
            $search_data['search_type'] = I('post.search_type') ? I('post.search_type') : $search_type;
            $search_data['uid'] = $user_id;
            $search_data['sort'] = $sort;
            $search_data['keyword'] = $keyword;
            $search_data['searchengine'] = get_source();
            $search_data['create_time'] = gmtime();
            $search_data['goods_num'] = $total ? $total : 0;
            $search = M('search_keyword');
            $search->add($search_data);
        }
    }


    //获取开放搜索 - 搜索列表结果
    protected function get_search_list($keyword, $start_offset=0, $sort_field='', $sort_type='', $user_rank=0){
        $search = new \Vendor\OpenSearch\CloudsearchSearch($this->client);
        $search->addIndex($this->app_name);
        $search->setHits($this->page_size);  //返回条数
        $search->setStartHit($start_offset);  //设置返回结果的offset偏移量(从第几条开始)
        $search->setQueryString("default:'$keyword'"); // 指定搜索关键词// AND (origin:'俄罗斯' OR origin:'塞浦路斯')

        //$search->addSort("s".$this->wid, '-');
        $search->setFormulaName("text_relevance_test");
        if($sort_field){
            $sort_type = $sort_type ? $sort_type : '-';
            $price = $user_rank==2 ? 'vip_money' : 'money';
            if($sort_field == 'shop_price')
                $search->addSort($price, $sort_type);
            elseif($sort_field == 'comment')
                $search->addSort("comment_conut", $sort_type);
            else
                die('sort_field参数有误');
        }

        //处理虚拟仓id
        $wid = in_array($this->wid, array(15,19,20)) ? 8 : $this->wid;



        $search->addFilter('is_on_sale=1');
        $search->addFilter('is_alone_sale=1');
        $search->addFilter('is_delete=0');
        $search->addFilter('wid='. $wid);

        //品牌筛选
        if($this->brand_id){
            $search->addFilter('contain(brand_id, "'.$this->brand_id.'")');
        }

        //产地筛选
        if($this->origin){
            $search->addFilter('contain(origin, "'.$this->origin.'")');
        }

        //分类筛选
        if($this->cat_id){
            $search->addFilter('contain(cat_id, "'.$this->cat_id.'")');
        }

       // $search->addFilter('wid='.$this->wid);
        $search->setFormat("json");
        $search->addDistinct('goods_id', 1, 1, 'false', '', 'true');

        $json = $search->search();
        $result = json_decode($json,true);
        //print_r($this->client->getRequest());//exit;
        //print_r($result);exit;

        return $result['result'];
    }

    //获取当前搜索 - 品牌列表
    protected function get_brand($keyword){
        $brand_list = array();
        $data = $this->get_search_type($keyword, 'get_brand');
        foreach ($data['items'] as $key=>$value){
            $brand_list[$key]['id'] = $value['brand_id'];
            $brand_list[$key]['brand_name'] = $value['brand_name'];
        }
        return $brand_list;
    }

    //获取当前搜索 - 产地列表
    protected function get_origin($keyword){
        $origin_list = array();
        $data = $this->get_search_type($keyword, 'get_origin');
        foreach ($data['items'] as $key=>$value){
            if($value['origin'])
                $origin_list[] = $value['origin'];
        }
        rsort($origin_list);
        return $origin_list;
    }

    //获取当前搜索 - 分类列表
    public function get_category($keyword, $cat_id_list=''){
        $opensearch = new OpensearchService();

        $category_list = array();
        $data = $this->get_search_type($keyword, 'get_category', $cat_id_list);

        foreach ($data['items'] as $key=>$value){
            $category_id[] = $value['cat_id'];
        }

        if(!empty($category_id)){
            $map['cat_id'] = array('in', implode(',',$category_id));
            $map['is_show'] = array('neq', 0);
            $category_list = $opensearch->get_category_list($map);
        }

        return $category_list;

    }

    //获取子分类
    protected function get_son_category($keyword, $cat_id_list){

        $opensearch = new OpensearchService();

        $category_list = array();
        $data = $this->get_search_type($keyword, 'get_son_category', $cat_id_list);


        foreach ($data['items'] as $key=>$value){
            $category_id[] = $value['cat_id'];
        }

        if(!empty($category_id)){
            $map['cat_id'] = array('in', implode(',',$category_id));
            $map['is_show'] = array('neq', 0);
            $category_list = $opensearch->get_son_category_list($map);
        }

        return $category_list;
    }

    //获取开放搜索 - 搜索类型
    protected function get_search_type($keyword, $key, $cat_id_list=''){
        $search = new \Vendor\OpenSearch\CloudsearchSearch($this->client);
        $search->addIndex($this->app_name);
        $search->setHits(500);
        $search->setQueryString("default:'$keyword'");
        $search->addFilter('is_on_sale=1');
        $search->addFilter('is_alone_sale=1');
        $search->addFilter('is_delete=0');
        $search->addFilter('brand_id!=0');
        $search->addFilter('wid='.$this->wid);

        switch ($key){
            case 'get_brand':
                //分类筛选
                if($this->cat_id){
                    $search->addFilter('contain(cat_id, "'.$this->cat_id.'")');
                }
                //产地筛选
                if($this->origin){
                    $search->addFilter('contain(origin, "'.$this->origin.'")');
                }
                $search->addSort("brand_id", '+');
                $search->addDistinct('brand_id', 1, 1, 'false', '', 'true');
                break;
            case 'get_origin':
                //分类筛选
                if($this->cat_id){
                    $search->addFilter('contain(cat_id, "'.$this->cat_id.'")');
                }
                //品牌筛选
                if($this->brand_id){
                    $search->addFilter('contain(brand_id, "'.$this->brand_id.'")');
                }
                $search->addDistinct('origin', 1, 1, 'false', '', 'true');
                break;
            case 'get_son_category':
                //品牌筛选
                if($this->brand_id){
                    $search->addFilter('contain(brand_id, "'.$this->brand_id.'")');
                }
                //产地筛选
                if($this->origin){
                    $search->addFilter('contain(origin, "'.$this->origin.'")');
                }
                //分类筛选
                if($cat_id_list){
                    $search->addFilter('contain(cat_id, "'.$cat_id_list.'")');
                }
                $search->addDistinct('cat_id', 1, 1, 'false', '', 'true');
                break;
            case 'get_category':
                //分类筛选
                if($cat_id_list && $_POST['keyword']==''){
                    $search->addFilter('contain(cat_id, "'.$cat_id_list.'")');
                }
                $search->addDistinct('cat_id', 1, 1, 'false', '', 'true');
                break;
            case 'get_category_parent':

                //分类筛选（一级分类）
                $search->addDistinct('cat_id_1', 1, 1, 'false', '', 'true');

                break;
            default:
                return;
        }
        $search->setFormat("json");
        $json = $search->search();
        $result = json_decode($json,true);
        //print_r($result);exit;
        return $result['result'];
    }

    public function get_category_parent($keyword){
        $data = array();
        $category = $this->get_search_type($keyword, 'get_category_parent');

        $key = 0;
        foreach($category['items'] as $val){
            if($val['catname1']){
                $data[$key]['cat_name'] = $val['catname1'];
                $data[$key]['cat_id'] = $val['cat_id_1'];
                if($key >=2){
                    break;
                }
                $key++;
            }
        }
        return $data;
    }

    //搜索下拉词
    public function get_pulldown(){
        $keyword = I('keyword');
        $num = I('num',10);
        $num = $num > 10 ? 10 : $num;
        if(!$keyword || !$num){
            returnApiError('参数错误');
        }

        //获取关键词列表
        $keyword_list = $this->get_search_keyword($keyword);


        $data = array();
        foreach ($keyword_list as $key=>$value){
            $category = unserialize($value['category']);
            $data[$key]['suggestion'] = $value['keyword'];
            $data[$key]['category'] = count($category)>1 ? $category : array();
            //$data[$key]['category'] = $category;

        }

        if($data)
            returnApiSuccess(array('pulldown_list'=>$data));
        else
            returnApiError('无数据');






        $brand_list = array();
        $sdx_list = array();
        $pulldown_list = array();

        $pulldown_list = $this->get_aliyun_pulldown($keyword,$num,'category');
        if(count($pulldown_list)<$num){

            $brand_list = $this->get_aliyun_pulldown($keyword,$num,'brand');
            $pulldown_list = array_merge($pulldown_list,$brand_list);

            if(count($pulldown_list)<$num){
                $sdx_list = $this->get_aliyun_pulldown($keyword,$num,'sdx');
                $pulldown_list = array_merge($pulldown_list,$sdx_list);
            }

        }

        $pulldown_list = array_slice($pulldown_list,0,$num);

        if($pulldown_list)
            returnApiSuccess(array('pulldown_list'=>$pulldown_list));
        else
            returnApiError('无数据');
    }

    /*
     * 返回阿里云下拉词
     * Created By caicm
     * @param string $keyword 关键词
     * @param int $num 返回数量
     * @param string $suggest_name 规则名称
     *
     */
    protected function get_aliyun_pulldown($keyword, $num=10, $suggest_name='sdx'){
        $suggest = new \Vendor\OpenSearch\CloudsearchSuggest($this->client);
        $suggest->setIndexName($this->app_name);
        $suggest->setSuggestName($suggest_name);
        $suggest->setHits($num);		//返回条数
        $suggest->setQuery($keyword);			//查询关键词
        $result = json_decode($suggest->search(), true);
        return $result['suggestions'];
    }



    //设置当前一级分类id下的所有子分类id
    protected function set_cat_id($cat_id){

        $id_list[] = $cat_id;
        $res = M('Category')->where("parent_id={$cat_id}")->field('cat_id')->select();
        foreach ($res as $k){
            $res2 = array();
            $id_list[] = $k['cat_id'];
            $res2 = $res = M('Category')->where("parent_id={$k['cat_id']}")->field('cat_id')->select();
            foreach ($res2 as $kal){
                $id_list[] = $kal['cat_id'];
            }
        }
        $this->cat_id = implode('|',$id_list);

    }

    protected function get_goods_id($data){
        $id_list = array();
        foreach ($data as $key=>$value){
            if($value['goods_id']){
                $id_list[] = $value['goods_id'];
            }
        }
        return $id_list;
    }

    /*
     * 搜索历史记录
     * Created By caicm
     * @param int $uid 用户id
     * return mixed
     */
    public function get_search_history(){
        $uid = I('post.uid', 0, 'int');
        if(!$uid){
            returnApiError('uid is null');
        }

        $opensearch = new OpensearchService();
        $search_history = $opensearch->get_history($uid, 1);

        //添加行为
        $user_bevavior = new UserBehavior();
        $val = $user_bevavior->add_browse($uid, 32);

        if($search_history)
            returnApiSuccess(array('histroy_list'=>$search_history));
        else
            returnApiError('无数据');

    }

    /*
     * 删除历史记录
     * Created By caicm
     * @param int $uid 用户id
     * return mixed
     */
    public function del_history(){
        $uid = I('post.uid', 0, 'int');
        if(!$uid){
            returnApiError('uid is null');
        }

        $val = M('search_keyword')->where(array('uid'=>$uid))->save(array('is_history_del'=>1));

        if($val){
            //添加行为
            $user_bevavior = new UserBehavior();
            $user_bevavior->add_browse($uid, 33);
            returnApiSuccess(null,'操作成功！');
        }else{
            returnApiError('操作失败！');
        }


    }


    /*
     * 根据搜索关键词获取近义词信息
     * Created By caicm
     * @param string $keyword 搜索关键词
     * @param int $page 分页
     * @param int $uid 用户id
     * @param int $wid 仓库id
     * return mixed
     */
    public function get_synonym(){

        $keyword = I('post.keyword');
        $page_num = I('post.page',1, 'int');
        $this->wid = I('post.wid',8, 'int');
        $user_id = I('post.uid',0, 'int');

        if(!$keyword){
            returnApiError('keyword is null');
        }

        //同义词数据
        $synonym_list = M('synonym')->field('synonym')->where(array('keyword'=>$keyword))->select();

        if(!$synonym_list){
            returnApiError('没数据');
        }

        $opensearch = new OpensearchService();

        $synonym_data = array();
        foreach ($synonym_list as $value){
            $synonym_data[] = $value['synonym'];
        }


        //查询会员等级
        if($user_id){
            $user = M("Users")->field('user_rank')->find($user_id);
        }

        $firstpage = ($page_num-1) * $this->page_size;
        $search_list = $this->get_search_list($synonym_data[0], $firstpage, $sort_field, $sort_type, $user['user_rank']);

        $id_list = $this->get_goods_id($search_list['items']);

        if(!$id_list) returnApiError('没有数据');

        $goods_list = D('Goods')->get_search_goods_by_id(implode(',', $id_list), $user_id, $this->wid);

        $return_data = array();
        $return_data['synonym_data'] = $synonym_data;
        $pagecount = ceil($search_list['total']/$this->page_size);

        if($pagecount <= $page_num){
            //判断是否为最后一页
            $return_data['is_bottom'] = 1;
        }else{
            $return_data['is_bottom'] = 0;
        }
        $return_data['total'] = $search_list['total'];
        $return_data['page'] = array(
            'firstpage' => $firstpage,
            'pagecount' => $pagecount,
            'pagesize' => $this->page_size
        );
        $return_data['goodssaleslist'] = $goods_list;

        returnApiSuccess($return_data);

    }


    /*
     * 搜索关键词处理
     */
    public function search_keyword_dispose($keyword){
        $this->page_size = 1;
        //通过关键词获取搜索结果
        $search_list = $this->get_search_list($keyword);
        return  $search_list['items'][0]['catname3'];
    }

    /*
     * 获取关键词搜索结果（keyword_pulldown）
     */
    protected function get_search_keyword($keyword){
        if(!$keyword){
            return false;
        }
        $search = new \Vendor\OpenSearch\CloudsearchSearch($this->client);
        $search->addIndex('keyword_pulldown');
        $search->setHits(10);
        $search->setQueryString("keyword:'$keyword'");
        $search->addSort("num", '-');
        $search->setFormat("json");
        $json = $search->search();
        $result = json_decode($json,true);
        return $result['result']['items'];
    }







}